package com.czx.drivingtest.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author czx
 * @version 2021/2/3 9:58 下午
 */
public class ServletUtils {
    /**
     * 得到当前request
     * @return
     */
    public static HttpServletRequest currentServletRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        return request;
    }
    /**
     * 得到session
     * @return
     */
    public static HttpSession currentHttpSession() {
        return currentServletRequest().getSession();
    }

    /**
     * 获取session中的某一项值
     * @param key
     * @return
     */
    public static Object getSessionAttribute(String key) {
        return currentHttpSession().getAttribute(key);
    }

    /**
     * 得到当前的响应对象
     * @return
     */
    public static HttpServletResponse currentServletResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 获取请求头
     * @param header
     * @return
     */
    public static String getRequestHeader(String header) {
        HttpServletRequest request = currentServletRequest();
        return request.getHeader(header);
    }
}
